//极简配置
const CONFIG = {
  BASE_URL: 'https://xhd.szxhdkj.com',
  CACHE_TIME: 6 * 60 * 60 * 1000, // 6小时
  DEFAULT_CITY: '深圳市'
};

// 引入轻量 i18n 工具
const i18n = require('../../i18n/index');

Component({
  properties: {
    pageTitle: { type: String, value: '智能水杯' },
    pageIcon: { type: String, value: '💧' },
    pageTip: { type: String, value: '记录每一滴水，健康生活每一天' },
    userName: { type: String, value: '' },
    showCycleInfo: { type: Boolean, value: false },
    cyclePhaseIcon: { type: String, value: '' },
    cyclePhase: { type: String, value: '' },
    cycleDay: { type: Number, value: 0 },
    cycleSuggestion: { type: String, value: '' }
  },
  
  data: {
    currentDate: '',
    currentWeekDay: '',
    weatherTemp: '--',
    weatherCondition: '获取中...',
    weatherCity: '定位中...',
    cycleDayText: ''
  },

  observers: {
    'cycleDay': function(value) {
      this.updateCycleDay(value);
    }
  },

  lifetimes: {
    attached() {
      this.updateTexts();
      this.updateDateTime();
      this.initWeather();
      
      // 监听语言切换，实时刷新本地化内容
      this.langUnsub = i18n.onLangChange(() => {
        this.updateTexts();
        this.updateDateTime();
        // 天气状态提示（如正在获取/暂无天气）依赖语言
        const loadingText = i18n.t('header.weatherLoading');
        if (this.data.weatherCondition === '获取中...' || this.data.weatherCondition === loadingText) {
          this.setData({ weatherCondition: loadingText });
        } else {
          // 直接用缓存中的原始 condition/city 重新本地化
          this.relocalizeWeatherFromCache();
        }
      });
      
      // 每分钟更新时间
      this.timeInterval = setInterval(() => {
        this.updateDateTime();
      }, 60000);
    },

    detached() {
      if (this.timeInterval) {
        clearInterval(this.timeInterval);
      }
      if (this.langUnsub) {
        try { this.langUnsub(); } catch (_) {}
      }
    }
  },

  methods: {
    // 刷新依赖语言的静态文本
    updateTexts() {
      // 定位中文案与默认天气文案
      this.setData({
        weatherCondition: this.data.weatherCondition && this.data.weatherCondition !== '获取中...'
          ? this.data.weatherCondition
          : i18n.t('header.weatherLoading'),
        weatherCity: i18n.t('header.locating')
      });
      this.updateCycleDay(this.data.cycleDay);
    },

    // 更新日期时间（本地化）
    updateDateTime() {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');

      // 星期本地化
      const dict = i18n.getDict();
      const weekDays = (dict.header && dict.header.weekdays) || ['周日','周一','周二','周三','周四','周五','周六'];

      // 日期格式本地化
      const lang = i18n.getLang();
      let dateStr = `${year}年${month}月${day}日`;
      if (lang === 'en-US') {
        // 简单 MM/DD/YYYY
        dateStr = `${month}/${day}/${year}`;
      } else if (lang === 'zh-HK') {
        dateStr = `${year}年${month}月${day}日`;
      }
      
      this.setData({
        currentDate: dateStr,
        currentWeekDay: weekDays[now.getDay()]
      });
    },

    updateCycleDay(day) {
      const text = i18n.t('header.cycleDay', { day: day || 0 });
      this.setData({ cycleDayText: text });
    },

    // 从缓存重本地化天气与城市
    relocalizeWeatherFromCache() {
      const today = new Date().toISOString().split('T')[0];
      const cached = wx.getStorageSync(`weather_${today}`);
      if (!cached) return;
      const condition = this.localizeCondition(cached.rawCondition != null ? cached.rawCondition : cached.condition);
      const city = this.localizeCity(cached.rawCity || cached.city || CONFIG.DEFAULT_CITY);
      const weatherCondition = condition || i18n.t('header.sunny');
      const weatherCity = city || CONFIG.DEFAULT_CITY;
      this.setData({ weatherCondition, weatherCity });
    },

    // 初始化天气
    initWeather() {
      const today = new Date().toISOString().split('T')[0];
      const cached = wx.getStorageSync(`weather_${today}`);
      
      // 检查缓存
      if (cached && cached.time && (Date.now() - cached.time) < CONFIG.CACHE_TIME) {
        const cachedCondition = cached.rawCondition != null ? cached.rawCondition : cached.condition;
        this.setData({
          weatherTemp: cached.temp || '--',
          weatherCondition: this.localizeCondition(cachedCondition) || i18n.t('header.sunny'),
          weatherCity: this.localizeCity(cached.rawCity || cached.city || CONFIG.DEFAULT_CITY)
        });
        return;
      }
      
      // 获取新天气数据
      this.getWeather();
    },

    // 获取天气
    getWeather() {
      wx.getSetting({
        success: (res) => {
          if (res.authSetting['scope.userLocation'] === false) {
            this.showLocationDialog();
          } else {
            this.getLocationWeather();
          }
        },
        fail: () => this.showDefaultWeather()
      });
    },

    // 位置权限对话框
    showLocationDialog() {
      wx.showModal({
        title: i18n.t('header.locationTitle'),
        content: i18n.t('header.locationContent'),
        confirmText: i18n.t('header.authorize'),
        cancelText: i18n.t('header.defaultOption'),
        success: (res) => {
          if (res.confirm) {
            wx.openSetting({
              success: (setting) => {
                if (setting.authSetting['scope.userLocation']) {
                  this.getLocationWeather();
                } else {
                  this.showDefaultWeather();
                }
              }
            });
          } else {
            this.showDefaultWeather();
          }
        }
      });
    },

    // 获取位置天气
    getLocationWeather() {
      wx.getLocation({
        type: 'gcj02',
        success: (location) => {
          const { latitude, longitude } = location;
          
          // 直接请求天气API，不做城市判断
          this.fetchWeather(`/api/weather/location?latitude=${latitude}&longitude=${longitude}`);
        },
        fail: () => this.showDefaultWeather()
      });
    },

    // 天气API请求
    fetchWeather(endpoint) {
      this.setData({ weatherCondition: i18n.t('header.weatherLoading') });
      
      wx.request({
        url: CONFIG.BASE_URL + endpoint,
        timeout: 10000,
        success: (res) => {
          if (res.statusCode === 200 && res.data?.data) {
            this.handleWeatherData(res.data.data);
          } else {
            this.showDefaultWeather();
          }
        },
        fail: () => this.showDefaultWeather()
      });
    },

    // 将天气原始中文/英文等描述本地化到当前语言
    localizeCondition(raw) {
      const text = (raw || '').toString();
      if (!text) return '';
      const map = i18n.getDict().header && i18n.getDict().header.weatherMap;
      if (map && map[text] != null) return map[text];
      // 默认直接返回原文
      return text;
    },

    // 城市名本地化（中英互转，可扩展更多地区名）
    localizeCity(raw) {
      const text = (raw || '').toString();
      if (!text) return '';
      const map = i18n.getDict().header && i18n.getDict().header.cityMap;
      if (map && map[text] != null) return map[text];
      return text;
    },

    // 处理天气数据
    handleWeatherData(data) {
      const weather = data.data || data;
      
      const temp = weather.temperature || '--';
      const rawCondition = weather.condition || '';
      const condition = this.localizeCondition(rawCondition) || i18n.t('header.sunny');
      const rawCity = weather.city || CONFIG.DEFAULT_CITY;
      const weatherCity = this.localizeCity(rawCity);
      
      this.setData({
        weatherTemp: temp,
        weatherCondition: condition,
        weatherCity: weatherCity
      });
      
      // 缓存数据（保留原始描述，便于重新本地化）
      const today = new Date().toISOString().split('T')[0];
      wx.setStorageSync(`weather_${today}`, {
        temp, condition, rawCondition, city: weatherCity, rawCity, time: Date.now()
      });
    },

    // 显示默认天气
    showDefaultWeather() {
      this.setData({
        weatherTemp: '--',
        weatherCondition: i18n.t('header.noWeather'),
        weatherCity: this.localizeCity(CONFIG.DEFAULT_CITY)
      });
      
      // 缓存默认数据（短时间缓存，避免重复请求）
      const today = new Date().toISOString().split('T')[0];
      wx.setStorageSync(`weather_${today}`, {
        temp: '--', condition: i18n.t('header.noWeather'), rawCondition: '', city: CONFIG.DEFAULT_CITY, rawCity: CONFIG.DEFAULT_CITY, time: Date.now()
      });
    }
  }
});

